package com.demo2do.fms.admin.web.controller.supplier.sub.flow;

import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.demo2do.core.entity.page.Page;
import com.demo2do.core.entity.result.HttpResult;
import com.demo2do.core.web.interceptor.MenuSetting;
import com.demo2do.core.web.resolver.Preloading;
import com.demo2do.core.web.utils.WebUtils;
import com.demo2do.fms.admin.entity.search.supplier.SupplierAuditSearch;
import com.demo2do.fms.admin.entity.security.Login;
import com.demo2do.fms.admin.service.DataService;
import com.demo2do.fms.admin.service.supplier.SupplierAuditService;
import com.demo2do.fms.admin.service.supplier.SupplierService;
import com.demo2do.fms.admin.web.resolver.Secure;
import com.demo2do.fms.entity.supplier.common.AuditStatus;
import com.demo2do.fms.entity.supplier.common.Supplier;

/**
 * 分属备选供方审核
 * 
 *  一级供方可以看到所属他的所有二级供方列表，可以对其进行引入申报
 *  分区可以看到所属他的一级供方列表，并对其进行引入申报
 *  总部可以看到所有的供方列表，不过总部一般不进行引入申报
 * 
 * @author Wy
 *
 */
@Controller
@RequestMapping("/supplier-audits")
@MenuSetting("menu-supplier")
public class SupplierAuditController {
    
    private static final Logger logger = LoggerFactory.getLogger(SupplierAuditController.class);
    
    @Autowired
    private SupplierAuditService supplierAuditService;

    @Autowired
    private SupplierService supplierService;
    
    @Autowired
    @Qualifier("dataService")
    private DataService<Supplier> supplierDataService;
    
    /**
     * list
     * 
     * @param login
     * @param page
     * @param request
     * @return
     */
    @RequestMapping(value = "" , method = RequestMethod.GET)
    @MenuSetting("submenu-editing-supplier-management")
    public ModelAndView list(@Secure Login login, Page page,
                             HttpServletRequest request){
        
        ModelAndView modelAndView = new ModelAndView("supplier/sub/flow/supplier/supplier-audit-list");
        
        AuditStatus[] status = new AuditStatus[]{AuditStatus.EDITING, AuditStatus.REJECTED};
        
        if(login.isBranchUser() || login.isSuper()) {
            
            int totals = supplierAuditService.countSupplierByStatus(status);
            if(totals > 0) {
                
                List<Supplier> suppliers = supplierAuditService.listSupplierByStatus(status, page.with(totals));
                modelAndView.addObject("suppliers", suppliers);
                modelAndView.addObject("page", page);
                
            }
            
            modelAndView.addObject("queryString", WebUtils.extractQueryString(request, "page", "filter"));
            
        } else if(login.isSupplier()){
            
        	Supplier parent = supplierDataService.load(Supplier.class, login.getSupplierId());
            
        	int totals = supplierAuditService.countSupplierByStatus(status, parent);
            if(totals > 0) {
                
                List<Supplier> suppliers = supplierAuditService.listSupplierByStatus(status, parent, page.with(totals));
                modelAndView.addObject("suppliers", suppliers);
                modelAndView.addObject("page", page);
                
            }
            
            modelAndView.addObject("queryString", WebUtils.extractQueryString(request, "page", "filter"));
            
        }
        
        return modelAndView;
        
    }
    
    /**
     * search panel
     * 
     * @param page
     * @return
     */
    @RequestMapping(value = "/search" , method = RequestMethod.GET )
    @MenuSetting("submenu-editing-supplier-management")
    public ModelAndView search(Page page){
        ModelAndView modelAndView = new ModelAndView("supplier/sub/flow/supplier/supplier-audit-search");
        return modelAndView;
    }
    
    /**
     * on search
     * 
     * @param login
     * @param search
     * @param request
     * @param page
     * @return
     */
    @RequestMapping(value = "" , method = RequestMethod.GET  , params = "filter")
    @MenuSetting("submenu-editing-supplier-management")
    public ModelAndView onSearch(@Secure Login login, SupplierAuditSearch search, 
                                 HttpServletRequest request, Page page){
        
        ModelAndView modelAndView = new ModelAndView("supplier/sub/flow/supplier/supplier-audit-list");
        
        AuditStatus[] auditStatus= new AuditStatus[]{AuditStatus.EDITING, AuditStatus.REJECTED};
        search.setAuditStatus(auditStatus);

        if (login.isSupplier()) {
            List<Long> supplierIds = supplierService.listSubSupplierId(login);
            search.addSupplierIds(supplierIds);
        }
        
        int totals = supplierDataService.count(Supplier.class, search.getFilter());
        if(totals > 0) {
            
            List<Supplier> suppliers = supplierAuditService.searchSupplier(search, page);
            modelAndView.addObject("suppliers", suppliers);
            
            modelAndView.addObject("page", page);
            modelAndView.addObject("queryString", WebUtils.extractQueryString(request, "page", "filter"));
            
        }
        
        return modelAndView;
        
    }
    
    /**
     * 引入申报panel
     * 
     * @param supplierId
     * @param page
     * @return
     */
    @RequestMapping(value = "/{supplierId}/introduce" , method = RequestMethod.GET)
    public ModelAndView introduce(@PathVariable("supplierId") Long supplierId, Page page){
        
        ModelAndView modelAndView = new ModelAndView("supplier/sub/flow/supplier/supplier-audit-introduce");
        
        modelAndView.addObject("supplierId", supplierId);
        
        return modelAndView;
        
    }

    /**
     * 引入申报
     * 
     * @param operator
     * @param supplier
     * @return
     */
    @RequestMapping(value = "/{id}/introduce" , method = RequestMethod.PATCH, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public @ResponseBody HttpResult onIntroduce(@Secure(property = "id") Long operator, 
                                                @Preloading("supplierId") Supplier supplier) {
        
        HttpResult httpResult = new HttpResult();
        
        try {
            
            supplierAuditService.introduce(supplier, operator);
            
            httpResult.success().message("引入申报成功");
            
        } catch (Exception e) {
            httpResult.fail("500").message(e.getMessage());
            logger.error("#onIntroduce() - introduce audit fail, exception = [{}]", e);
        }
        
        return httpResult;
    }
    
}
